<template>
  <Container>
    <template v-slot:content>
      <div class="deviceRelatedDataItems">
        <div class="chooseArea">
          <TreeList titleName="选择区域" :treeList="areaList" :treeProps="{
            label: 'areaName',
            value: 'areaId',
            children: 'child'
          }" @getTreeNode="getTreeNode"></TreeList>
        </div>
        <div class="contentBox">
          <div class="btnList">
            <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
          </div>
          <div class="tableContent">
            <TableData :tableThead="tableThead" :config="table_config" :dataList="dataList" :page="page" :size="size"
              :loading="loading" :total="total" @selection-change="selectionChange"
              @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange">
            </TableData>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'设备'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
    </template>
  </Container>
</template>

<script>
import TreeList from "@/components/TreeList"
import Container from "@/components/Container"
import areaApi from '@/api/area'
import AddEdit from './components/addEdit.vue';
import equipmentApi from '@/api/equipment'

export default {
  name: 'EnergyOverview',
  components: {
    TreeList,
    Container,
    AddEdit
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      addEditFlag: 'add',
      btnList: ['add', 'delete'],
      areaList: [],
      size: 10,
      page: 1,
      total: 10,
      dataList: [],
      tableThead: [
        { label: '设备名称', prop: 'equipmentName' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    async initData() {
      let { data: areaList } = await areaApi.queryTreeByCondition({});
      this.areaList = areaList || [];
      this.getTreeNode(this.areaList[0] || {})
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.addEditFlag = 'add';
        this.dialogVisible = true;
      }
      if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
    },
    getDifference(array1, array2) {
      return array1.filter(element => !array2.includes(element));
    },
    delList(deleteList = [], key = 'equipmentId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(this.formData.equipmentIdList, list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await equipmentApi.bandArea({
          areaId: this.formData.areaId,
          equipmentIdList: this.getDifference(this.formData.equipmentIdList, list)
        });
        if (res.code == 1) {
          this.$message.success('删除成功');
          this.queryByCondition();
          this.queryPageByCondition();
        } else {
          this.$message.warning('删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'delete') {
        this.delList([rowData]);
      }
      this.addEditFlag = item.flag
    },
    getTreeNode(node) {
      this.formData = { ...node }
      this.searchFormData = {
        areaId: node.areaId
      }
      if (node.areaId) {
        this.queryByCondition();
        this.queryPageByCondition();
      }
    },
    queryByCondition() {
      this.loading = true;
      equipmentApi.queryByCondition({ ...this.searchFormData }).then(res => {
        this.loading = false;
        let chooseList = res.data;
        this.formData.equipmentIdList = chooseList.map(e => e.equipmentId)
      }).catch(err => {
        this.loading = false;
      })
    },
    //查询表单数据
    queryPageByCondition() {
      this.loading = true;
      equipmentApi.queryPageByCondition({
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          organizationNo:sessionStorage.organizationNo
        }
      }).then(res => {
        if (res.code == 1) {
          let { content, totalElements } = res.data || {}
          this.dataList = content || [];
          this.total = totalElements || 10;
        } else {
          this.dataList = [];
        }
        this.loading = false;
      }).catch(err => {
        this.loading = false;
      })
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryByCondition();
      this.queryPageByCondition();
    },
  }
}
</script>

<style lang="scss" scoped>
.deviceRelatedDataItems {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;

  .chooseArea {
    width: 20%;
    height: 100%;
    background: #FFFFFF;
    border-radius: 5px;
  }

  .contentBox {
    width: calc(80% - 10px);
    height: 100%;
    margin-left: 10px;

    .btnList {
      width: 100%;
      height: 48px;
      background: #FFFFFF;
      border-radius: 5px;
    }

    .tableContent {
      width: 100%;
      height: calc(100% - 58px);
      background: #FFFFFF;
      border-radius: 5px;
      margin-top: 10px;
      padding: 15px;
    }
  }
}
</style>
